<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/7/10
 * Time: 8:25
 */

namespace app\index\controller;

use think\Request;
use think\Exception;
use app\lib\exception\WeChatException;
use app\index\model\Token as TokenModel;

class Token extends BaseController
{
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxAccessTokenUrl;
    protected $wxBaseUrl;

    function __construct()
    {
        $this->wxAppID = config('wx.app_id');
        $this->wxAppSecret = config('wx.app_secret');
        $this->wxAccessTokenUrl = sprintf(config('wx.access_token_url'),$this->wxAppID,$this->wxAppSecret);
    }

    //1、获取accessToken
    public function getAccessToken(){
        //先从数据库中获取
        $data_now = time();
        $access_token_info = TokenModel::where('expired_time','>',$data_now)->find();  //find只返回满足查询条件的第一组数据
        if($access_token_info){
            return $access_token_info['access_token'];
        }

        //调取接口获取
        $path = $this->wxAccessTokenUrl;
        $wxResult = $this->send($path);
        $access_token = $wxResult['access_token'];
        $expired_time = time()+$wxResult['expires_in']-200;
        if(!$access_token){
            throw new WeChatException([
                'msg' => 'access_token获取失败'
            ]);
        }
        $token = TokenModel::create([
            'access_token' => $access_token,
            'expired_time' => $expired_time
        ]);
        return $token['access_token'];

    }
    //整合GET提交和POST提交
    public static function send($path, $data = [] ,$method = 'GET'){
        $request_url = config('wx.base_url').$path;
        if( $method == "POST") {
            $result = curl_post_raw($request_url,$data);
        }else{
            $result = curl_get($request_url);
        }
        $wxResult = json_decode($result,true);  //true为数组，false为对象
        if(empty($wxResult)) {
            throw new Exception('获取access_token异常，微信内部错误');
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail){
                throw new WeChatException([
                    'msg' => $wxResult['errmsg'],
                    'errorCode' => $wxResult['errcode'],
                ]);
            }
        }
        return $wxResult;
    }

    /**
     * 将access_token存储到session中
     */
    public function getWxAccessToken(){
        if($_SESSION['access_token']&&$_SESSION['expire_time']>time()){
            return $_SESSION['access_token'];
        }else{
            //调取接口获取
            $path = $this->wxAccessTokenUrl;
            $wxResult = $this->send($path);
            $access_token = $wxResult['access_token'];
            $_SESSION['access_token'] = $access_token;
            $_SESSION['expire_time'] = time()+7000;
            return $access_token;
        }
    }


}